package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.biz.utils.UnicodeUtil;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 逐鹿营销
 */
public class SmsApiZLYX extends GateWayHttpAbstract
{

    public SmsApiZLYX(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        String t = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Map<String,Object> params = Maps.newHashMap();
        params.put("apikey", paramsMaps.get("apikey"));
        params.put("mobile", mt.getPhone());
        try {
            params.put("content", URLEncoder.encode(mt.getSmsContent(),"UTF-8"));
            params.put("send_ts",URLEncoder.encode(t,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error("提交网关短信内容utf-8编码错误，网关:{}, 短信内容:{}", this.gateWayID, mt.getSmsContent());
        }
        String result =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/v1/sms/marketing/send", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        
        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);

        List<SMSSRMessage> resultList = Lists.newArrayList();

        SMSSRMessage message = initGatewayResultMessage(result, mt, "code");
        String resultCode = null;
        String resultMessage = null;
        String taskid = null;
        JSONObject object = JSON.parseObject(result);
        if(StringUtils.equals(message.getResult(), "F10199")) {
            resultCode = object.getString("code");
            resultMessage = object.getString("msg");
            taskid = object.getString("result");
            message.setMsgkey(mt.getPhone());
            setGatewayResultCode(message, taskid, resultCode, resultMessage, "1");
            resultList.add(message);
        }
        return resultList;
    }
    
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {
        if (StringUtils.isNotBlank(text)) {
            JSONArray result = JSON.parseArray(text);
            for(int i=0 ; i < result.size() ;i++){
                JSONObject data = result.getJSONObject(i);
                SMSRTMessage smsRtMessage = initSmsRtMessage(data.getString("serNo"), data.getString("account"),data.getString("account"),
                        data.getString("status"), "4");
                rtList.add(smsRtMessage);
            }
        }
        return new SmsHttpMsgResponse("success");
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
        SmsHttpMsgResponse smsHttpMsgResponse = new SmsHttpMsgResponse("0");
        if (StringUtils.isNotBlank(text)) {
            JSONArray result = JSON.parseArray(text);
            for(int i=0 ; i < result.size() ;i++){
                JSONObject data = result.getJSONObject(i);
                SMSMOMessage sMSMOMessage = new SMSMOMessage();
                sMSMOMessage.setGateWayID(gateWayID);
                sMSMOMessage.setMsgContent(UnicodeUtil.decode(data.getString("msg")));
                sMSMOMessage.setMsgid(data.getString("serNo"));
                sMSMOMessage.setPhone(data.getString("mobile"));
                sMSMOMessage.setSenttime(data.getString("sendTs"));
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
                sMSMOMessage.setUuid(UUID.randomUUID().toString());
                moList.add(sMSMOMessage);
            }
        }
        return smsHttpMsgResponse;
    }

    @Override
    public String queryReport(String jsonText) {
        return "";
    }

    @Override
    public String queryDeliver(String jsonText) {
        return "";
    }

    /**
     *
     * userid 用户名
     * account 账号
     * password 密码
     * action 任务名称 固定值overage
     * @return
     */
    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        String t = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        params.put("apikey",paramsMaps.get("apikey"));
        String result =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/v1/user/get" , Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
        if (StringUtils.isNotBlank(result)) {
            JSONObject userInfo = JSON.parseObject(result);
            if (StringUtils.equals(userInfo.getString("code"),"1")) {
                JSONObject info = JSON.parseObject(userInfo.getString("result"));
                return "余额：" + info.getString("balance") + ",警告条数:" + info.getString("warnSmsCount") + ",ip白名单：" + info.getString("whiteIps");
            }
        }
        return "余额查询失败";
    }
    
    public static void main(String[] args)
    {
        String params = "{\"userid\":\"13\",\"account\":\"qianxiang\",\"passwd\":\"qianxiang\",\"apiUrl\":\"http://39.107.53.239:8088\",\"statusNum\":\"4000\"}";
        SmsApiZLYX api = new SmsApiZLYX("ZY",params);
//        String balance = api.balance();
        SMSMTMessage message = new SMSMTMessage();
        message.setPhone("18268846802");
        message.setId("test123456");
        message.setSmsContent("【千橡科技】你的短信验证码是123456");
//        api.doSend(message);
        api.queryReport("");
//        System.out.println(DigestUtils.md5Hex("testmima20120701231212"));
    }
    
}